import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyImage.dart';

class MyDialog extends StatelessWidget {
  Widget dialog;

  MyDialog(this.dialog);

  @override
  Widget build(BuildContext context) {
    Duration insetAnimationDuration = const Duration(milliseconds: 100);
    Curve insetAnimationCurve = Curves.decelerate;
    return AnimatedPadding(
        padding: MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0),
        duration: insetAnimationDuration,
        curve: insetAnimationCurve,
        child: MediaQuery.removeViewInsets(
            removeLeft: true, removeTop: true, removeRight: true, removeBottom: true, context: context, child: Center(child: dialog)));
  }
}

class ScaffoldDialog extends StatelessWidget {
  Widget dialog;

  ScaffoldDialog(this.dialog);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      backgroundColor: MyColor.Transfer,
      body: MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        child: Center(
          child: dialog,
        ),
      ),
    );
  }
}

///只有文字的弹窗
class TextDialog extends StatelessWidget {
  String content;

  TextDialog(this.content);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 280,
      decoration: BoxDecoration(color: MyColor.White, borderRadius: BorderRadius.circular(8)),
      child: Material(
        color: MyColor.Transfer,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
                margin: EdgeInsets.only(right: 5),
                alignment: Alignment.centerRight,
                child: LocalImage("ic_close.png", width: 16, height: 16, padding: EdgeInsets.all(10), onTap: () {
                  Navigator.pop(context);
                })),
            Container(
                padding: EdgeInsets.fromLTRB(60, 10, 60, 36), child: Text(content, style: TextStyle(fontSize: 16, color: MyColor.Black)))
          ],
        ),
      ),
    );
  }
}

void showTextDialog(BuildContext context, String content) {
  showWidgetDialog(context, TextDialog(content));
}

/// 單按鈕dialog
class Btn1Dialog extends StatelessWidget {
  String title;
  String content;
  String btnText;
  Function()? onTap;

  Btn1Dialog(this.title, this.content, {this.btnText = "確認", this.onTap});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: Global.getWhiteBg(15),
      padding: EdgeInsets.fromLTRB(29, 28, 29, 38),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(title, style: TextStyle(fontSize: 18, color: MyColor.Black, fontWeight: FontWeight.bold)),
          Container(height: 12),
          Text(content, style: TextStyle(fontSize: 16, color: MyColor.C66)),
          Button(btnText, margin: EdgeInsets.only(top: 36), onTap: () {
            Navigator.pop(context);
            onTap?.call();
          })
        ],
      ),
    );
  }
}

void showBtn1Dialog(BuildContext context, String title, String content, {String btnText = "確認", Function()? onTap}) {
  showWidgetDialog(context, Btn1Dialog(title, content, btnText: btnText, onTap: onTap));
}

/// 雙按鈕dialog
class Btn2Dialog extends StatelessWidget {
  String content;
  String btn1Text;
  Function on1Tap;
  String btn2Text;
  Function on2Tap;

  Btn2Dialog(this.content, this.btn1Text, this.on1Tap, this.btn2Text, this.on2Tap);

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getWhiteBg(8),
        padding: EdgeInsets.fromLTRB(18, 20, 18, 20),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text(content, style: TextStyle(fontSize: 14, color: MyColor.C58)),
          Container(height: 29),
          Row(mainAxisSize: MainAxisSize.min, children: [
            TextBtn(btn1Text, height: 28, width: 64, style: TextStyle(fontSize: 13, color: MyColor.Orange), onTap: () {
              Navigator.pop(context);
              on1Tap();
            }),
            Container(width: 15),
            Button(btn2Text, height: 28, width: 64, radius: 4, fontSize: 13, bgColor: MyColor.Orange, fontColor: MyColor.White, onTap: () {
              Navigator.pop(context);
              on2Tap();
            })
          ])
        ]));
  }
}

void showBtn2Dialog(BuildContext context, String content, String btn1Text, Function on1Tap, String btn2Text, Function on2Tap) {
  showWidgetDialog(context, Btn2Dialog(content, btn1Text, on1Tap, btn2Text, on2Tap));
}

void showScaffoldBtn2Dialog(
    BuildContext context, String content, String btnLeftText, Function onLeftTap, String btnRightText, Function onRightTap) {
  showScaffoldDialog(context, Btn2Dialog(content, btnLeftText, onLeftTap, btnRightText, onRightTap));
}

/// 自定義弹窗
void showWidgetDialog(BuildContext context, Widget dialog) {
  showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) {
        return MyDialog(dialog);
      });
}

void showScaffoldDialog(BuildContext context, Widget dialog) {
  showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) {
        return ScaffoldDialog(dialog);
      });
}

void showBottomDialog(BuildContext context, Widget dialog) {
  showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      builder: (context) {
        return dialog;
      });
}

///底部滾輪選擇器
void showWheelDialog(BuildContext context, String title, List<dynamic> menus, Function(int index) onSelected) {
  showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      builder: (context) {
        return wheelView(title, menus, onSelected);
      });
}

void showWheelDialog2(BuildContext context, String title, List<dynamic> menus, String key, Function(int index) onSelected) {
  List<String> strMenus = [];
  for (var item in menus) {
    strMenus.add(item[key]);
  }
  showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      builder: (context) {
        return wheelView(title, strMenus, onSelected);
      });
}

class wheelView extends StatelessWidget {
  String title;
  List<dynamic> menus;
  Function(int index) onSelected;
  int selectIndex = 0;

  wheelView(this.title, this.menus, this.onSelected);

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            TextBtn("取消", height: 57, margin: EdgeInsets.fromLTRB(15, 0, 15, 0), onTap: () {
              PageUtil().back(context);
            }),
            Text(title, style: TextStyle(color: MyColor.Black, fontSize: 16, fontWeight: FontWeight.bold)),
            TextBtn("完成", height: 57, margin: EdgeInsets.fromLTRB(15, 0, 15, 0), onTap: () {
              PageUtil().back(context);
              onSelected(selectIndex);
            }),
          ]),
          Divider(height: 1, color: MyColor.E9),
          Container(
              height: 200,
              child: CupertinoPicker.builder(
                selectionOverlay: Column(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                  Divider(height: 1, color: MyColor.E9, endIndent: 15, indent: 15),
                  Divider(height: 1, color: MyColor.E9, endIndent: 15, indent: 15),
                ]),
                childCount: menus.length,
                diameterRatio: 2,
                squeeze: 1,
                onSelectedItemChanged: (index) {
                  selectIndex = index;
                  print("onSelectedItemChanged:$index");
                },
                itemExtent: 40,
                itemBuilder: (BuildContext context, int index) {
                  return TextBtn("${menus[index]}", height: 40);
                },
              ))
        ]));
  }
}

///底部菜單選擇器
void showMenuDialog(BuildContext context, List<String> menus, Function(int index) onSelected) {
  showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      builder: (context) {
        return MenuView(menus, onSelected);
      });
}

class MenuView extends StatelessWidget {
  List<String> menus;
  Function(int index) onSelected;

  MenuView(this.menus, this.onSelected);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: menus.length + 1,
      itemBuilder: (BuildContext context, int index) {
        return index == menus.length
            ? TextBtn("取消", height: 48, width: double.infinity, style: TextStyle(fontSize: 14), onTap: () {
                PageUtil().back(context);
              })
            : TextBtn(menus[index], height: 48, width: double.infinity, style: TextStyle(fontSize: 14), onTap: () {
                PageUtil().back(context);
                onSelected(index);
              });
      },
      separatorBuilder: (BuildContext context, int index) {
        return Container(height: 0.5, color: MyColor.EE);
      },
    );
  }
}

///註冊成功
class RegisterSuccess extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [Text("註冊成功，登入密碼為電話號碼，如需修改密碼請至會員編輯個人資料"), TextBtn("我知道了", height: 32)],
      ),
    );
  }
}

///下載進度條
class DownloadDialog extends StatefulWidget {
  List<dynamic> classedUrls = [];

  DownloadDialog(this.classedUrls);

  @override
  State<StatefulWidget> createState() {
    return _DownloadDialog();
  }
}

class _DownloadDialog extends State<DownloadDialog> {
  int progress = 0;
  int total = 1;
  int downloadIndex = 0;

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      download(0);
    });
    super.initState();
  }

  download(int index) {
    downloadIndex = index;
    if (index == widget.classedUrls.length) {
      PageUtil().back(context);
      return;
    }
    String savePath = Global.downloadPath + "/hitutor_${widget.classedUrls[index]["fileName"]}";
    print(savePath);

    // MethodChannel _channel = MethodChannel('PathUtil');
    // _channel.invokeMethod(
    //     "downloadFile", <String, String>{'url': widget.classedUrls[index]["url"], 'filename': widget.classedUrls[index]["fileName"]});

    HttpGo(context).download(widget.classedUrls[index]["url"], savePath, (progress, total) {
      this.progress = progress;
      this.total = total;
      setState(() {});
    }, () {
      download(index + 1);
      setState(() {});
    }, (code, error) {
      download(index + 1);
      showToast(error);
    });
  }

  @override
  Widget build(BuildContext context) {
    String totalSize = "未知大小";
    String downloadSize = "";
    if (total > 0) {
      totalSize = (total / 1000000).toStringAsFixed(2) + "M";
    }
    if (progress > 0) {
      downloadSize = (progress / 1000000).toStringAsFixed(2) + "M";
    }
    return Container(
        padding: EdgeInsets.all(24),
        margin: EdgeInsets.all(32),
        decoration: Global.getBg(MyColor.White, 8),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text("正在下載第${downloadIndex + 1} / ${widget.classedUrls.length}個文件"),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 12),
              child: LinearProgressIndicator(value: progress / total, color: MyColor.Orange, backgroundColor: Color(0xffffeade)),
            ),
            Text("$downloadSize / $totalSize"),
            Button("取消下載", height: 36, radius: 4, bgColor: MyColor.Orange, margin: EdgeInsets.only(top: 12), onTap: () {
              PageUtil().back(context);
            })
          ],
        ));
  }
}

///Toast
void showToast(String msg) {
  // SmartDialog.showToast(msg, type: SmartToastType.last);
  SmartDialog.showToast(msg,
      type: SmartToastType.last,
      widget: Container(
        margin: EdgeInsets.all(48),
        decoration: Global.getBg(MyColor.Black75, 12),
        padding: EdgeInsets.all(12),
        child: Text(msg, style: TextStyle(color: MyColor.White, height: 1.4)),
      ));
}

///Loading
class LoadingWidget extends StatelessWidget {
  String msg;

  LoadingWidget({this.msg = "loading..."});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: Global.getBg(Colors.black87, 12),
      padding: EdgeInsets.symmetric(vertical: 24, horizontal: 32),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          CircularProgressIndicator(
            strokeWidth: 3,
            valueColor: AlwaysStoppedAnimation(Colors.white),
          ),
          Container(
            margin: EdgeInsets.only(top: 20),
            child: Text(msg, style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }
}
